/* eslint-disable no-mixed-operators */
import React, { PureComponent } from 'react';

import Temperature from './demo53';
// 根据温度 -> 渲染结果
const BoilingVerdict = (props) => {
  if (props.celsius >= 100) {
    return <p>水烧开了</p>;
  } else {
    return <p>水还没有烧开</p>;
  }
};

function toCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5 / 9;
}

function toFahrenheit(celsius) {
  return (celsius * 9 / 5) + 32;
}
function tryConvert(temperature, convert) {
  const input = parseFloat(temperature);
  if (Number.isNaN(input)) {
    return '';
  }
  const output = convert(input);
  const rounded = Math.round(output * 1000) / 1000;
  return rounded.toString();
}

// 温度计算器
class Calculator extends PureComponent {
  state = {
    temperature: '',
    scale: 'c',
  };

  handleCelsiusChange = (temperature) => {
    this.setState({ scale: 'c', temperature });
  };
  handleFahrenheitChange = (temperature) => {
    this.setState({ scale: 'f', temperature });
  };

  // handleChange = (e) => {
  //   this.setState({ temperature: e.target.value });
  // };

  // render() {
  //   const { temperature } = this.state;
  //   return (
  //     <fieldset>
  //       <legend>输入一个摄氏度</legend>
  //       <input
  //         value={temperature}
  //         onChange={this.handleChange}
  //       />
  //       <BoilingVerdict celsius={parseFloat(temperature)} />
  //     </fieldset>
  //   );
  // }
  render() {
    const { temperature, scale } = this.state;
    const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
    const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;
    return (
      <div>
        <Temperature scale="c" temperature={celsius} onTemperatureChange={this.handleCelsiusChange} />
        <Temperature scale="f" temperature={fahrenheit} onTemperatureChange={this.handleFahrenheitChange} />
        <BoilingVerdict celsius={parseFloat(celsius)} />
      </div>
    );
  }
}

export default Calculator;

